//
//  main.m
//  parseiosdemo
//
//  Created by XuLiang on 2017/2/13.
//  Copyright © 2017年 XuLiang. All rights reserved.
//

#import <Foundation/Foundation.h>

NSMutableArray *filesArry;
NSMutableArray *needCheckFilesArry;
NSMutableArray *keyArry;


//所有符合正则的文件.m .mm
void searchAllFiles(NSString *strPatch){
    //创建NSFileManager实例
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error;
    //目录下的所有文件及文件夹
    NSArray *fileContentsArry = [fm contentsOfDirectoryAtPath:strPatch error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
//    NSLog(@"%@",fileContentsArry);
    //检测目录下的文件夹
    for (NSString *tempStr in fileContentsArry) {
        NSString *patchStr = [strPatch stringByAppendingString:[NSString stringWithFormat:@"/%@",tempStr]];
        if ([fm fileExistsAtPath:patchStr]) {
            searchAllFiles(patchStr);
        }
    }
    
    NSString *pattern = @"\.m$|\.swift$";

    for (NSString *tempStr in fileContentsArry) {
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
        //测试字符串
        NSArray *results = [regex matchesInString:tempStr options:0 range:NSMakeRange(0, tempStr.length)];
        if (results.count > 0) {
            NSDictionary *fileDic = @{@"name":tempStr,@"filePath":[strPatch stringByAppendingString:[NSString stringWithFormat:@"/%@",tempStr]]};
            [filesArry addObject:fileDic];
//            NSLog(@"%zd,filename=%@", results.count,tempStr);
        }
    }
}

void searchLocalizedFile(NSString *superPath){
    //创建NSFileManager实例
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error;
    //目录下的所有文件及文件夹
    NSArray *fileContentsArry = [fm contentsOfDirectoryAtPath:superPath error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    //检测目录下的文件夹
    for (NSString *tempStr in fileContentsArry) {
        
        NSString *pattern = @"Localizable.strings";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
        //测试字符串
        NSArray *results = [regex matchesInString:tempStr options:0 range:NSMakeRange(0, tempStr.length)];
        NSString *patchStr = [superPath stringByAppendingString:[NSString stringWithFormat:@"/%@",tempStr]];
        if (results.count > 0) {
            NSLog(@"%@",tempStr);
            //读出国际化的Key
            NSData *datas = [fm contentsAtPath:patchStr];
            NSString *dataStr = [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
            NSString *pattern2 = @"\"[^\"]+\" =";
            NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:pattern2 options:0 error:nil];
            if (!dataStr) {
                return;
            }
            NSArray *results = [regex2 matchesInString:dataStr options:0 range:NSMakeRange(0, dataStr.length)];
            if (results.count > 0){
                for (NSTextCheckingResult *checkresult in results){
                    NSString *localStringStr = [dataStr substringWithRange:checkresult.range];
                    NSString *pattern2 = @"\"[^\"]+\"";
                    NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:pattern2 options:0 error:nil];
                    NSTextCheckingResult *localCheckingResult = [regex2 firstMatchInString:localStringStr options:0 range:NSMakeRange(0, localStringStr.length)];
                    if (localCheckingResult.range.location != NSNotFound){
                        NSString *LocalizedString = [[localStringStr substringWithRange:localCheckingResult.range] stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                        [keyArry addObject:LocalizedString];
                    }
                }
            }
        }
        if ([fm fileExistsAtPath:patchStr]) {
            searchLocalizedFile(patchStr);
        }
    }
}

//筛选文件中可查验的文件
void searchNeedFiles(NSArray *dataA){
    //读取所有文件的数组
    for (NSDictionary *fileData in dataA) {
        NSString *fileName = [fileData objectForKey:@"name"];
        NSString *filePath = [fileData objectForKey:@"filePath"];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        
        NSData *datas = [fm contentsAtPath:filePath];
        NSString *dataStr = [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
        if (dataStr && (dataStr.length > 0)) {
            NSString *pattern = @"NSLocalizedString\s*\\(\s*@\"[^\"]+\"|NSLocalizedString\s*\\(\s*\"[^\"]+\"";
            NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
            NSArray *results = [regex matchesInString:dataStr options:0 range:NSMakeRange(0, dataStr.length)];
            if (results.count > 0) {
                [needCheckFilesArry addObject:fileData];
            }
        }
    }
}

//查验文件key时候符合
void checkParseInFile(NSString *strPatch){
    NSFileManager *fm = [NSFileManager defaultManager];
    NSData *datas = [fm contentsAtPath:strPatch];
    NSString *dataStr = [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSString *pattern = @"NSLocalizedString\s*\\(\s*@\"[^\"]+\"|NSLocalizedString\s*\\(\s*\"[^\"]+\"";//@"NSLocalizedString\s*\\(\s*@\"[^\"]+\"";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
    NSArray *results = [regex matchesInString:dataStr options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, dataStr.length)];
    if (results.count > 0) {
        for (NSTextCheckingResult *checkresult in results) {
//            NSLog(@"%llu,%lu,%lu",checkresult.resultType,(unsigned long)checkresult.range.location,(unsigned long)checkresult.range.length);
            NSString *localStringStr = [dataStr substringWithRange:checkresult.range];
            NSString *pattern2 = @"\"[^\"]+\"";
            NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:pattern2 options:0 error:nil];
            NSTextCheckingResult *localCheckingResult = [regex2 firstMatchInString:localStringStr options:0 range:NSMakeRange(0, localStringStr.length)];
            
            if (localCheckingResult.range.location != NSNotFound) {
//                NSLog(@"%@", [localStringStr substringWithRange:localCheckingResult.range]);
                NSString *LocalizedString = [[localStringStr substringWithRange:localCheckingResult.range] stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                //找出文件中的国际化比对
                //如果 找不到 输出文件名 key名
                if (LocalizedString && [keyArry containsObject:LocalizedString]){
                    
                }else{
                    NSLog(@"不存在Key“%@”",LocalizedString);
                }
            }
        }
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        filesArry = [NSMutableArray array];//需要检测的文件
        needCheckFilesArry = [NSMutableArray array];//需要检测的文件
        keyArry = [NSMutableArray array];//
        NSLog(@"键入项目地址，如/Users/XXXXX/Documents/GitWorkSpace/SmartHomeV5\n");
        printf("键入项目地址，如/Users/XXXXX/Documents/GitWorkSpace/SmartHomeV5\n");
        ////////////////
        char *cstring = malloc(sizeof(char) * 1000);
        scanf("%s", cstring);
        NSString *inputFilePachString = [NSString stringWithUTF8String:cstring];
        if (inputFilePachString.length <= 0) {
            NSLog(@"无法识别路径");
            return 0;
        }else{
            NSLog(@"输入的路径为：%@",inputFilePachString);
        }
        ////////////////
        NSString *filePach = inputFilePachString;//@"/Users/xuliang/Documents/GitWorkSpace/SmartHomeV5";//总目录
        searchLocalizedFile(filePach);
        NSLog(@"==========================================================\n国际化Key读取成功，共：%lu个\n",(unsigned long)keyArry.count);
        searchAllFiles(filePach);
        NSLog(@"==========================================================\n需要检查的文件，共：%lu个\n",(unsigned long)filesArry.count);
        //目录下所有符合正则的文件
//        NSLog(@"filesArry=%@",filesArry);
        searchNeedFiles(filesArry);
        NSLog(@"==========================================================\n有国际化的文件，共：%lu个\n",(unsigned long)needCheckFilesArry.count);
        //目录下所有符合正则的文件
//        NSLog(@"needCheckFilesArry=%@",needCheckFilesArry);
        
        //开始查验Key
        for (int i = 0;i < needCheckFilesArry.count;i++) {
            NSDictionary *fileData = (NSDictionary *)[needCheckFilesArry objectAtIndex:i];
            NSString *fileName = [fileData objectForKey:@"name"];
            NSString *filePath = [fileData objectForKey:@"filePath"];
            checkParseInFile(filePath);
            if (!(i%20) || i == needCheckFilesArry.count-1) {
                NSLog(@"==========================================================\n检查完成了%.0f%%\n==========================================================\n",i*100.0/(needCheckFilesArry.count-1));
            }
        }
    }
    return 0;
}
